package com.yummy.cloud.gateway.handler;

import java.util.Map;

import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.error.ErrorAttributeOptions.Include;
import org.springframework.boot.web.reactive.error.DefaultErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.web.reactive.function.server.ServerRequest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yummy.convention.exception.BusinessException;
import com.yummy.convention.http.Response;

public class YummyErrorAttributes extends DefaultErrorAttributes{
	
	public YummyErrorAttributes() {
		super();
	}

	@Override
	public Map<String, Object> getErrorAttributes(ServerRequest request, ErrorAttributeOptions options) {
		Throwable error = getError(request);
		if(error instanceof BusinessException) {
			return businessErrorAttributes(error);
		}
		return super.getErrorAttributes(request,ErrorAttributeOptions.of(Include.MESSAGE));
	}
	
	private Map<String,Object> businessErrorAttributes(Throwable error) {
		JSONObject jo = (JSONObject) JSON.toJSON(Response.failure(determinErrorCode(error), determineErrorMessage(error)));
		jo.put("status", HttpStatus.OK.value());
		return jo;
	}

	private String determineErrorMessage(Throwable error) {
		return error.getMessage();
	}

	private String determinErrorCode(Throwable error) {
		if(error instanceof BusinessException) {
			BusinessException be = (BusinessException) error;
			if(be.getErrorCode() != null) {
				return be.getErrorCode();
			}
		}
		return String.valueOf(HttpStatus.INTERNAL_SERVER_ERROR.value());
	}
	
}
